﻿using System;
using System.Collections.Generic;
using System.Linq;

namespace ARchGL.Platform
{
    public static class AbpExtensions
    {
        /// <summary>
        /// 集合是否有值
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="list"></param>
        /// <returns></returns>
        public static bool Any<T>(this List<T> list)
        {
            return list != null && list?.Count > 0;
        }

        /// <summary>
        /// 返回10位时间戳 Timestamp
        /// </summary>
        /// <param name="target"></param>
        /// <param name="length"></param>
        /// <returns></returns>
        public static long ToUnixTimestamp(this DateTime target, int length = 10)
        {
            //if (target.Kind == DateTimeKind.Unspecified)
            //    target = target.ToLocalTime();
            var ticks = (target.ToUniversalTime().Ticks - 621355968000000000);

            switch (length)
            {
                case 10: return ticks / 10000000; //10位时间戳
                case 13: return ticks / 10000; //13位时间戳
                default: return ticks / 10000000;
            }
        }

        /// <summary>
        /// 将10位时间戳Timestamp转换成日期
        /// </summary>
        /// <param name="target"></param>
        /// <returns></returns>
        public static DateTime ToLocalDateTime(this int target)
        {
            var date = new DateTime(621355968000000000 + (long)target * (long)10000000, DateTimeKind.Local);
            return date.ToLocalTime();
        }

        /// <summary>
        /// 将10位时间戳Timestamp转换成日期
        /// </summary>
        /// <param name="target"></param>
        /// <returns></returns>
        public static DateTime ToLocalDateTime(this long target)
        {
            return ToLocalDateTime(int.Parse(target.ToString()));
        }

        /// <summary>
        /// 验证指定长度的MD5
        /// </summary>
        /// <param name="str">字符串</param>
        /// <param name="length">MD5长度（默认32）</param>
        /// <returns></returns>
        public static bool IsMd5(this string str, int length = 32)
        {
            if (str.Length < length || str.Length > length)
                return false;

            int count = 0;
            var charArray = "0123456789abcdefABCDEF".ToCharArray();

            foreach (var c in str.ToCharArray())
            {
                if (charArray.Any(x => x == c))
                    ++count;
            }
            return count == length;
        }
    }
}
